<?php
/**
 * Created by PhpStorm.
 * User: DELL-PC
 * Date: 2018/9/5
 * Time: 9:41
 */

namespace J\MVC;


use J\Exception;
use J\Intent;

abstract class Actor
{
    /**
     * @var Controller
     */
    protected $controller;

    /**
     * @var Department
     */
    protected $department;

    /**
     * AutoController constructor.
     * @param $controller
     */
    public function __construct(Controller $controller)
    {
        $this->controller = $controller;

        $controller->addMiddleware(function (\Closure $next) {
            return function(Intent $intent) use ($next) {
                // 首先执行内核
                $r = $next($intent);
                // 内核执行成功直接返回
                if ($r !== false) return $r;
                return $this->act($intent);
            };
        });
    }

    /**
     * 中间件动作
     *
     * @param Intent $intent
     * @return null|false
     * @throws Exception
     */
    abstract protected function act(Intent $intent);

    /**
     * @return \J\Schema\ICollection
     * @throws \J\Exception
     */
    protected function getModel()
    {
        return $this->controller->getCollection();
    }

    protected function filterAdd($array)
    {
        if ($this->department)
            $array = $this->department->add($array);
        return $array;
    }

    protected function filterRemove($array)
    {
        if ($this->department)
            $array = $this->department->remove($array);
        return $array;
    }
}